import React, { useState, useEffect } from 'react';
import { useNavigate, useLocation } from 'react-router-dom';
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
import { Button } from '@/components/ui/button';
import { Progress } from '@/components/ui/progress';
import { useVocabulary } from '@/contexts/VocabularyContext';
import { selectRandomWords, getWordCountByDifficulty, generateWrongOptions, shuffleArray } from '@/utils/gameHelpers';
import { ArrowLeft, Trophy, Clock } from 'lucide-react';
import type { Category, Word } from '@/types/vocabulary';

interface Question {
  word: Word;
  question: string;
  correctAnswer: string;
  options: string[];
  type: 'en-to-zh' | 'zh-to-en';
}

const QuizGame: React.FC = () => {
  const navigate = useNavigate();
  const location = useLocation();
  const { getWordsByCategory, settings, updateQuizStats, updateCategoryStats } = useVocabulary();
  const category = (location.state?.category as Category) || '全部类别';

  const [questions, setQuestions] = useState<Question[]>([]);
  const [currentIndex, setCurrentIndex] = useState(0);
  const [selectedAnswer, setSelectedAnswer] = useState<string | null>(null);
  const [correctCount, setCorrectCount] = useState(0);
  const [score, setScore] = useState(0);
  const [timeLeft, setTimeLeft] = useState(settings.timeLimit);
  const [isGameComplete, setIsGameComplete] = useState(false);
  const [questionStartTime, setQuestionStartTime] = useState(Date.now());

  useEffect(() => {
    initializeGame();
  }, []);

  useEffect(() => {
    if (!isGameComplete && !selectedAnswer && timeLeft > 0) {
      const timer = setTimeout(() => {
        setTimeLeft((prev) => prev - 1);
      }, 1000);
      return () => clearTimeout(timer);
    } else if (timeLeft === 0 && !selectedAnswer) {
      handleTimeout();
    }
  }, [timeLeft, isGameComplete, selectedAnswer]);

  const initializeGame = () => {
    const allWords = getWordsByCategory(category);
    const wordCount = getWordCountByDifficulty(settings.difficulty);
    const selectedWords = selectRandomWords(allWords, wordCount);

    const generatedQuestions: Question[] = selectedWords.map((word) => {
      const type = Math.random() > 0.5 ? 'en-to-zh' : 'zh-to-en';
      const question = type === 'en-to-zh' ? word.english : word.chinese;
      const correctAnswer = type === 'en-to-zh' ? word.chinese : word.english;
      const wrongOptions = generateWrongOptions(
        correctAnswer,
        allWords,
        type === 'zh-to-en',
        3
      );
      const options = shuffleArray([correctAnswer, ...wrongOptions]);

      return {
        word,
        question,
        correctAnswer,
        options,
        type,
      };
    });

    setQuestions(generatedQuestions);
    setCurrentIndex(0);
    setCorrectCount(0);
    setScore(0);
    setTimeLeft(settings.timeLimit);
    setIsGameComplete(false);
    setSelectedAnswer(null);
    setQuestionStartTime(Date.now());
  };

  const handleTimeout = () => {
    setSelectedAnswer('timeout');
    setTimeout(() => {
      moveToNextQuestion();
    }, 1500);
  };

  const handleAnswerSelect = (answer: string) => {
    if (selectedAnswer) return;

    setSelectedAnswer(answer);
    const currentQuestion = questions[currentIndex];
    const isCorrect = answer === currentQuestion.correctAnswer;

    updateCategoryStats(currentQuestion.word.category, isCorrect);

    if (isCorrect) {
      setCorrectCount((prev) => prev + 1);
      const timeBonus = Math.floor((timeLeft / settings.timeLimit) * 20);
      setScore((prev) => prev + 100 + timeBonus);
    }

    setTimeout(() => {
      moveToNextQuestion();
    }, 1500);
  };

  const moveToNextQuestion = () => {
    if (currentIndex + 1 < questions.length) {
      setCurrentIndex((prev) => prev + 1);
      setSelectedAnswer(null);
      setTimeLeft(settings.timeLimit);
      setQuestionStartTime(Date.now());
    } else {
      setIsGameComplete(true);
      updateQuizStats(score, correctCount, questions.length);
    }
  };

  if (questions.length === 0) {
    return (
      <div className="min-h-screen bg-gradient-to-br from-blue-50 via-white to-purple-50 flex items-center justify-center">
        <div className="text-center">
          <p className="text-xl text-gray-600">加载中...</p>
        </div>
      </div>
    );
  }

  const progress = questions.length > 0 ? ((currentIndex + 1) / questions.length) * 100 : 0;
  const accuracy = questions.length > 0 ? Math.round((correctCount / questions.length) * 100) : 0;
  const timeProgress = (timeLeft / settings.timeLimit) * 100;

  if (isGameComplete) {
    return (
      <div className="min-h-screen bg-gradient-to-br from-blue-50 via-white to-purple-50 flex items-center justify-center p-4">
        <Card className="max-w-md w-full">
          <CardContent className="pt-6">
            <div className="text-center space-y-6">
              <Trophy className="w-20 h-20 text-yellow-500 mx-auto" />
              <h2 className="text-3xl font-bold text-gray-900">测验完成！</h2>
              <div className="space-y-3">
                <div className="flex items-center justify-between text-lg">
                  <span className="text-gray-600">总得分：</span>
                  <span className="font-semibold text-blue-600 text-2xl">{score}</span>
                </div>
                <div className="flex items-center justify-between text-lg">
                  <span className="text-gray-600">正确数量：</span>
                  <span className="font-semibold text-green-600">{correctCount}</span>
                </div>
                <div className="flex items-center justify-between text-lg">
                  <span className="text-gray-600">错误数量：</span>
                  <span className="font-semibold text-red-600">{questions.length - correctCount}</span>
                </div>
                <div className="flex items-center justify-between text-lg">
                  <span className="text-gray-600">准确率：</span>
                  <span className="font-semibold">{accuracy}%</span>
                </div>
              </div>
              <div className="flex gap-3">
                <Button onClick={() => navigate('/')} variant="outline" className="flex-1">
                  返回首页
                </Button>
                <Button onClick={initializeGame} className="flex-1">
                  再测一次
                </Button>
              </div>
            </div>
          </CardContent>
        </Card>
      </div>
    );
  }

  const currentQuestion = questions[currentIndex];

  // 计算圆形进度
  const circumference = 2 * Math.PI * 45; // 半径45
  const strokeDashoffset = circumference - (timeLeft / settings.timeLimit) * circumference;

  return (
    <div className="min-h-screen bg-gray-100 p-4">
      <div className="container mx-auto max-w-3xl">
        {/* 顶部导航栏 */}
        <div className="flex items-center justify-between mb-8">
          <Button variant="ghost" onClick={() => navigate('/')} className="bg-white hover:bg-gray-50">
            <ArrowLeft className="w-4 h-4 mr-2" />
            返回
          </Button>
          <div className="flex items-center gap-8">
            <div className="text-lg font-semibold">
              问题: {currentIndex + 1}/{questions.length}
            </div>
            <div className="text-lg font-semibold">
              得分: {score}
            </div>
          </div>
        </div>

        {/* 游戏标题和说明 */}
        <div className="text-center mb-8">
          <h1 className="text-3xl font-bold text-gray-900 mb-3">快速测验游戏</h1>
          <p className="text-gray-600">在规定时间内选择正确答案，挑战你的词汇反应速度。</p>
        </div>

        {/* 圆形倒计时器 */}
        <div className="flex justify-center mb-8">
          <div className="relative w-32 h-32">
            <svg className="transform -rotate-90 w-32 h-32">
              <circle
                cx="64"
                cy="64"
                r="45"
                stroke="#E5E7EB"
                strokeWidth="8"
                fill="none"
              />
              <circle
                cx="64"
                cy="64"
                r="45"
                stroke="#EC4899"
                strokeWidth="8"
                fill="none"
                strokeDasharray={circumference}
                strokeDashoffset={strokeDashoffset}
                strokeLinecap="round"
                className="transition-all duration-1000 ease-linear"
              />
            </svg>
            <div className="absolute inset-0 flex items-center justify-center">
              <span className="text-4xl font-bold text-gray-900">{timeLeft}</span>
            </div>
          </div>
        </div>

        {/* 中文提示 */}
        <div className="text-center mb-8">
          <p className="text-5xl font-bold text-gray-900">{currentQuestion.question}</p>
        </div>

        {/* 选项按钮 */}
        <div className="max-w-2xl mx-auto grid grid-cols-2 gap-4">
          {currentQuestion.options.map((option, index) => {
            const isSelected = selectedAnswer === option;
            const isCorrect = option === currentQuestion.correctAnswer;
            const showResult = selectedAnswer !== null;

            let buttonClass = 'h-20 text-lg justify-start border-2 bg-white hover:bg-gray-50 text-black';
            if (showResult) {
              if (isCorrect) {
                buttonClass = 'h-20 text-lg justify-start bg-green-500 hover:bg-green-600 text-white border-green-500';
              } else if (isSelected && !isCorrect) {
                buttonClass = 'h-20 text-lg justify-start bg-red-500 hover:bg-red-600 text-white border-red-500';
              }
            }

            return (
              <Button
                key={index}
                onClick={() => handleAnswerSelect(option)}
                disabled={!!selectedAnswer}
                variant="outline"
                className={buttonClass}
              >
                <span className="font-bold text-xl mr-3 min-w-[32px]">
                  {String.fromCharCode(65 + index)}
                </span>
                <span className="text-left">{option}</span>
              </Button>
            );
          })}
        </div>

        {selectedAnswer === 'timeout' && (
          <div className="text-center mt-6 p-4 bg-orange-100 text-orange-800 rounded-lg max-w-2xl mx-auto">
            <p className="font-semibold text-lg">时间到！正确答案是: {currentQuestion.correctAnswer}</p>
          </div>
        )}
      </div>
    </div>
  );
};

export default QuizGame;
